package cn.wowjoy.office.common.widget.album.preview;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;

import android.graphics.drawable.BitmapDrawable;
import android.support.v4.view.ViewPager;

import android.os.Bundle;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;

import java.util.ArrayList;


import cn.wowjoy.office.R;

import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.adapter.ImagePagerAdapter;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.mock.Image;
import cn.wowjoy.office.databinding.ActivityPhotoPreviewBinding;

import static android.animation.ObjectAnimator.ofFloat;
@Route(path = "/common/widget/album/preview/photopreview")
public class PhotoPreviewActivity extends NewBaseActivity<ActivityPhotoPreviewBinding,PhotoPreviewViewModel> {




    //tempImages和tempSelectImages用于图片列表数据的页面传输。
    //之所以不要Intent传输这两个图片列表，因为要保证两位页面操作的是同一个列表数据，同时可以避免数据量大时，
    // 用Intent传输发生的错误问题。
    private static ArrayList<Image> tempImages;
    private static ArrayList<Image> tempSelectImages;
    private ArrayList<Image> mImages;
    private ArrayList<Image> mSelectImages;
    private boolean isShowBar = true;
    private boolean isConfirm = false;
    private boolean isSingle;
    private int mMaxCount;

    private BitmapDrawable mSelectDrawable;
    private BitmapDrawable mUnSelectDrawable;



    public static void openActivity(Activity activity, ArrayList<Image> images,
                                    ArrayList<Image> selectImages, boolean isSingle,
                                    int maxSelectCount, int position) {
        tempImages = images;
        tempSelectImages = selectImages;
        Intent intent = new Intent(activity, PhotoPreviewActivity.class);
        intent.putExtra(Constants.MAX_SELECT_COUNT, maxSelectCount);
        intent.putExtra(Constants.IS_SINGLE, isSingle);
        intent.putExtra(Constants.POSITION, position);
        activity.startActivityForResult(intent, Constants.RESULT_CODE);
    }



    @Override
    protected void init(Bundle savedInstanceState) {
      initData();
      initView();


    }
    private void initData(){
        setStatusBarVisible(false);
        binding.setViewModel(viewModel);
        mImages = tempImages;
        tempImages = null;
        mSelectImages = tempSelectImages;
        tempSelectImages = null;
        Intent intent = getIntent();
        mMaxCount = intent.getIntExtra(Constants.MAX_SELECT_COUNT, 0);
        isSingle = intent.getBooleanExtra(Constants.IS_SINGLE, false);
    }
    private void initView(){
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        binding.complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isConfirm = true;
               onBackPressed();
            }
        });
        binding.selectedFl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSelect();
            }
        });
        ImagePagerAdapter adapter = new ImagePagerAdapter(this, mImages);
        binding.vpImage.setAdapter(adapter);
        adapter.setOnItemClickListener(new ImagePagerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Image image) {
                if (isShowBar) {
                    hideBar();
                } else {
                    showBar();
                }
            }
        });
        binding.vpImage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                binding.indicator.setText("预览（"+(position + 1) + "/" + mImages.size()+"）");
                changeSelect(mImages.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        binding.indicator.setText("预览（"+1 + "/" + mImages.size()+"）");
        changeSelect(mImages.get(0));
        binding.vpImage.setCurrentItem(getIntent().getIntExtra(Constants.POSITION, 0));
    }

    private void changeSelect(Image image) {
        binding.selected.setSelected(mSelectImages.contains(image));
        setSelectImageCount(mSelectImages.size());
    }

    private void clickSelect() {
        int position = binding.vpImage.getCurrentItem();
        if (mImages != null && mImages.size() > position) {
            Image image = mImages.get(position);
            if (mSelectImages.contains(image)) {
                mSelectImages.remove(image);
            } else if (isSingle) {
                mSelectImages.clear();
                mSelectImages.add(image);
            } else if (mMaxCount <= 0 || mSelectImages.size() < mMaxCount) {
                mSelectImages.add(image);
            }
            changeSelect(image);
        }
    }



    private void setSelectImageCount(int count) {
        if (count == 0) {
            binding.complete.setEnabled(false);
            binding.complete.setText("确定");
        } else {
            binding.complete.setEnabled(true);
            if (isSingle) {
                binding.complete.setText("确定");
            } else if (mMaxCount > 0) {
                binding.complete.setText("确定(" + count + "/" + mMaxCount + ")");
            } else {
                binding.complete.setText("确定(" + count + ")");
            }
        }
    }


    /**
     * 显示头部和尾部栏
     */
    private void showBar() {
        isShowBar = true;
        ObjectAnimator animator = ofFloat(binding.toolbar, "translationY",
                        binding.toolbar.getTranslationY(), 0).setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        super.onAnimationStart(animation);
                        binding.toolbar.setVisibility(View.VISIBLE);}
                });
        animator.start();

        ObjectAnimator animator1 = ofFloat(binding.bottomBar, "translationY", binding.bottomBar.getTranslationY(), 0)
                .setDuration(300);
        animator1.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                binding.bottomBar.setVisibility(View.VISIBLE);
            }
        });
        animator1.start();

    }

    /**
     * 隐藏头部和尾部栏
     */
    private void hideBar() {
        isShowBar = false;
        ObjectAnimator animator = ObjectAnimator.ofFloat(binding.toolbar, "translationY",
                0, -binding.toolbar.getHeight()).setDuration(300);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                binding.toolbar.setVisibility(View.GONE);
            }
        });
        animator.start();

        ObjectAnimator animator1 = ofFloat(binding.bottomBar, "translationY", 0, binding.bottomBar.getHeight())
                .setDuration(300);
        animator1.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                binding.bottomBar.setVisibility(View.GONE);
            }
        });
        animator1.start();
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_photo_preview;
    }

    @Override
    protected Class<PhotoPreviewViewModel> getViewModel() {
        return PhotoPreviewViewModel.class;
    }

    @Override
    public void onBackPressed() {
        //Activity关闭时，通过Intent把用户的操作(确定/返回)传给ImageSelectActivity。
        Intent intent = new Intent();
        intent.putExtra(Constants.IS_CONFIRM, isConfirm);
        setResult(Constants.RESULT_CODE, intent);
        super.onBackPressed();
    }
}
